#define _CRT_SECURE_NO_WARNINGS 1
#include <queue>
#include <iostream>
using namespace std;
  struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {}
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  };
 
using pin = pair<int, TreeNode*>;
class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum)
    {
        if (root == nullptr) return false;
        //if(root->val==targetSum&&root->left==nullptr&&root->right==nullptr) return true;
        queue<pin> q;
        q.push({ root->val,root });
        while (!q.empty())
        {
            int cnt = q.size();
            while (cnt--)
            {
                auto a = q.front().first;
                auto b = q.front().second;
                q.pop();
                if (b->left == nullptr && b->right == nullptr && a == targetSum) return true;
                if (b->left != nullptr)
                {
                    q.push({ a + b->left->val,b->left });
                }
                if (b->right != nullptr)
                {
                    q.push({ a + b->right->val,b->right });
                }
            }
        }
        return false;
    }
};